from django.shortcuts import render,redirect
from app01 import models
from app01.utilss.pagination import Paginator
from app01.utilss.forms import AdminModelForm
from app01.utilss.secery import md5

def admin_list(request):
    search_keyword = request.GET.get('search', '')
    paginator = Paginator(request, models.Admin.objects.all(), search_keyword, search_field='username')
    queryset = paginator.get_paginated_queryset()
    if not queryset.exists():
        search_message = "未找到符合条件的管理员。"
    else:
        search_message = ""
    context = {
        'queryset': queryset,
        'page_str_list': paginator.get_page_control_html(),
        'page': paginator.page,
        'total_page_count': paginator.total_page_count,
        'search_message': search_message,
        'request': request,
    }

    return render(request, 'admin_list.html', context)

def admin_add(request):
    if request.method == 'GET':
        form = AdminModelForm()
        return render(request, 'admin_add.html', {'form': form})
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.instance.password = md5(form.instance.password)
        form.save()
        return redirect('/admin/list/')
    else:
        return render(request, 'admin_add.html', {'form': form})

def admin_edit(request, nid):
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return redirect('/admin/list/')  # 如果管理员不存在，重定向到列表页

    if request.method == 'GET':
        form = AdminModelForm(instance=row_object)
        return render(request, 'admin_edit.html', {'form': form})

    form = AdminModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.instance.password = md5(form.instance.password)
        form.save()
        return redirect('/admin/list/')
    else:
        return render(request, 'admin_edit.html', {'form': form})

def admin_delete(request):
    nid = request.GET.get('nid')
    models.Admin.objects.filter(id=nid).delete()
    return redirect('/admin/list/')